package com.company.cloud.coupon.modules.mgr.controller;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.LocalDateTimeUtils;
import com.company.cloud.coupon.constant.CouponConstant.CouponActStateEnum;
import com.company.cloud.coupon.constant.CouponConstant.CouponObjType;
import com.company.cloud.coupon.constant.CouponConstant.CouponStateEnum;
import com.company.cloud.coupon.modules.base.entity.CouponConfigInfo;
import com.company.cloud.coupon.modules.base.entity.CouponFissionActInfo;
import com.company.cloud.coupon.modules.base.entity.CouponFissionInfo;
import com.company.cloud.coupon.modules.base.entity.CouponInfo;
import com.company.cloud.coupon.modules.base.service.CouponConfigInfoService;
import com.company.cloud.coupon.modules.base.service.CouponFissionActInfoService;
import com.company.cloud.coupon.modules.base.service.CouponFissionInfoService;
import com.company.cloud.coupon.modules.base.service.CouponInfoService;
import com.company.cloud.coupon.modules.cache.models.CouponFissionActModel;
import com.company.cloud.coupon.modules.cache.utils.CouponChangeUtils;
import com.company.cloud.coupon.modules.mgr.controller.req.CouponFissionQuery4PageParam;
import com.company.cloud.coupon.modules.mgr.controller.req.CouponFissionSaveParam;
import com.company.cloud.coupon.modules.mgr.controller.req.CouponFissionUpdateParam;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 裂变优惠券信息管理
 */
@Authc
@RestController
@RequestMapping("/mgr/op/couponFission")
@Api(tags="OP_Mgr_裂变优惠券配置信息管理")
public class CouponFissionActMgrController {
	
	@Autowired
	private CouponFissionActInfoService couponFissionActInfoService;
	@Autowired
	private CouponConfigInfoService couponConfigInfoService;
	@Autowired
	private CouponFissionInfoService couponFissionInfoService;
	@Autowired
	private CouponInfoService couponInfoService;
	
	@PostMapping("/query")
	@ApiOperation(value="查询", response=CouponFissionActModel.class)
	public BaseResult query(@RequestBody CouponFissionQuery4PageParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		IPage<CouponFissionActInfo> page = couponFissionActInfoService.page(new Page<>(params.getPage(), params.getRows()), 
				new QueryWrapper<CouponFissionActInfo>()
				.eq("rows_state", EnabledEnum.ENABLED.getCode())
				.eq("company_no", userInfo.getCompanyNo())
				.eq(StringUtils.hasText(params.getState()), "state", params.getState())
				.like(StringUtils.hasText(params.getName()), "name", params.getName())
				.orderByDesc("cdt")
				);

		Map<Integer, CouponConfigInfo> couponConfigMap=new HashMap<Integer, CouponConfigInfo>();
		if(!CollectionUtils.isEmpty(page.getRecords())) {
			Set<Integer> ccIds=new HashSet<Integer>();
			page.getRecords().forEach(item->{
				ccIds.add(item.getCouponConfigId());
			});
			Collection<CouponConfigInfo> couponConfigList=couponConfigInfoService.listByIds(ccIds);
			if(!CollectionUtils.isEmpty(couponConfigList)) {
				couponConfigList.forEach(item->{
					couponConfigMap.put(item.getId(), item);
				});
			}
		}
		
		IPage<CouponFissionActModel> data=page.convert(new Function<CouponFissionActInfo, CouponFissionActModel>() {
			@Override
			public CouponFissionActModel apply(CouponFissionActInfo entity) {
				return CouponChangeUtils.getCouponFissionAct(entity,couponConfigMap);
			}
		});
		return BaseResult.ok(data);
	}
	
	
	@PostMapping("/add")
	@ApiOperation(value="新增", response=BaseResult.class)
	public BaseResult add(@RequestBody CouponFissionSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		CouponFissionActInfo entity=new CouponFissionActInfo();
		entity.setCompanyNo(userInfo.getCompanyNo());
		entity.setName(params.getName());
		entity.setStarDate(LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getStarDate()));
		entity.setEndDate(LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getEndDate()));
		entity.setCouponConfigId(params.getCouponConfigId());
		entity.setCouponGiveNum(params.getCouponGiveNum());
		entity.setMaxIndex(params.getMaxIndex());
		entity.setMemberGetNumType(params.getMemberGetNumType());
		entity.setMemberGetNum(params.getMemberGetNum());
		entity.setState(CouponActStateEnum.CFS_ING.getCode());
		entity.addCreateParam(userInfo);
		entity.addEditParam(userInfo);
		couponFissionActInfoService.save(entity);
		return BaseResult.ok();
	}
	
	@PostMapping("/edit")
	@ApiOperation(value="修改", response=BaseResult.class)
	public BaseResult edit(@RequestBody CouponFissionUpdateParam params) {
		ValidatorUtils.validate(params);
		CouponFissionActInfo entity=couponFissionActInfoService.getById(params.getId());
		if(entity==null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		if(!CouponActStateEnum.CFS_Invalid.getCode().equals(entity.getState())) {
			throw new BusinessException("失效优惠券不能操作");
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		entity.setName(params.getName());
		entity.setEndDate(LocalDateTimeUtils.parse_yyyyMMddHHmmss(params.getEndDate()));
		entity.setCouponGiveNum(params.getCouponGiveNum());
		entity.setMaxIndex(params.getMaxIndex());
		entity.addEditParam(userInfo);
		couponFissionActInfoService.updateById(entity);
		return BaseResult.ok();
	}
	
	@GetMapping("/get")
	@ApiOperation(value="获取", response=CouponFissionActModel.class)
	public BaseResult get(@RequestParam("id")Integer id) {
		CouponFissionActInfo entity=couponFissionActInfoService.getById(id);
		if(entity==null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		CouponConfigInfo couponConfig=couponConfigInfoService.getById(entity.getCouponConfigId());
		
		CouponFissionActModel data=CouponChangeUtils.getCouponFissionAct(entity,couponConfig);
		
		int sendNum= couponFissionInfoService.count(new QueryWrapper<CouponFissionInfo>()
				.eq("coupon_fission_act_id", id));
		
		int giveNum= couponInfoService.count(new QueryWrapper<CouponInfo>()
				.eq("source_biz_type", CouponObjType.CouponFission_ObjType)
				.inSql("source_biz_id",StrUtil.format(
						"select id from op_coupon_fission_info where coupon_fission_act_id={}",id))
				);
		
		
		int useNum= couponInfoService.count(new QueryWrapper<CouponInfo>()
				.in("state", CouponStateEnum.Yes_Pay_CouponState.getCode(),CouponStateEnum.Yes_Scan_CouponState.getCode())
				.eq("source_biz_type", CouponObjType.CouponFission_ObjType)
				.inSql("source_biz_id",StrUtil.format(
						"select id from op_coupon_fission_info where coupon_fission_act_id={}",id))
				);
		
		data.setSendNum(sendNum);
		data.setGiveNum(giveNum);
		data.setUseNum(useNum);
		
		return BaseResult.ok(data);
	}
	
	@GetMapping("/remove")
	@ApiOperation(value="删除", response=BaseResult.class)
	public BaseResult remove(@RequestParam("id")Integer id) {
		CouponFissionActInfo entity=couponFissionActInfoService.getById(id);
		if(entity==null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		entity.setRowsState(EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		couponFissionActInfoService.updateById(entity);
		return BaseResult.ok();
	}
	
	
	@GetMapping("/invalid")
	@ApiOperation(value="优惠券失效", response=BaseResult.class)
	public BaseResult invalid(@RequestParam("id")Integer id) {
		CouponFissionActInfo entity=couponFissionActInfoService.getById(id);
		if(entity==null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		if(CouponActStateEnum.CFS_Invalid.getCode().equals(entity.getState())) {
			return BaseResult.ok();
		}
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		entity.setState(CouponActStateEnum.CFS_Invalid.getCode());
		entity.addEditParam(userInfo);
		couponFissionActInfoService.updateById(entity);
		return BaseResult.ok();
	}
	
	
	
}
